-- jdtls 配置
local jdtls_path = 'F:/jdt-language-server-1.9.0-202203031534/'
local workspace_dir = 'C:/Users/86159/.cache/jdtls-workspace/'

-- Lombok 配置
local lombok_path = jdtls_path .. 'lombok.jar'

-- 检查路径是否存在
local function check_path(path, name)
	if vim.fn.isdirectory(path) == 0 and vim.fn.filereadable(path) == 0 then
		vim.notify(name .. " 路径不存在: " .. path, vim.log.levels.WARN)
		return false
	end
	return true
end

-- 在启动前检查路径
if not check_path(jdtls_path, "jdtls") then
	return
end

local jdtls_config = {
	cmd = {
		'java',
		-- Lombok 支持
		'-javaagent:' .. lombok_path,
		'-Xbootclasspath/a:' .. lombok_path,

		'-Declipse.application=org.eclipse.jdt.ls.core.id1',
		'-Dosgi.bundles.defaultStartLevel=4',
		'-Declipse.product=org.eclipse.jdt.ls.core.product',
		'-Dlog.protocol=true',  -- 开启协议日志用于调试
		'-Dlog.level=ALL',      -- 详细日志

		-- 内存优化
		'-Xms1g',               -- 增加初始堆内存
		'-Xmx2g',               -- 增加最大堆内存
		'-XX:+UseG1GC',         -- 使用 G1 垃圾收集器
		'-XX:+UseStringDeduplication', -- 字符串去重

		'--add-modules=ALL-SYSTEM',
		'--add-opens', 'java.base/java.util=ALL-UNNAMED',
		'--add-opens', 'java.base/java.lang=ALL-UNNAMED',
		'-jar', vim.fn.glob(jdtls_path .. 'plugins/org.eclipse.equinox.launcher_*.jar'),
		'-configuration', jdtls_path .. 'config_win',
		'-data', workspace_dir
	},
	root_dir = require('jdtls.setup').find_root({'.git', 'mvnw', 'gradlew', 'pom.xml', 'build.gradle'}),

	init_options = {
		bundles = {},
		extendedClientCapabilities = {
			classFileContentsSupport = true,
			generateJavadocSupport = true,
			progressReportProvider = true
		}
	},

	settings = {
		java = {
			signatureHelp = { enabled = true },
			contentProvider = { preferred = 'fernflower' },
			completion = {
				enabled = true,
				favoriteStaticMembers = {
					"org.junit.Assert.*",
					"org.junit.Assume.*",
					"org.junit.jupiter.api.Assertions.*",
					"org.mockito.Mockito.*",
					"org.mockito.ArgumentMatchers.*",
					"org.mockito.Answers.*"
				},
				importOrder = {
					"java",
					"javax",
					"org",
					"com"
				}
			},
			sources = {
				organizeImports = {
					starThreshold = 9999,
					staticStarThreshold = 9999
				}
			},
			configuration = {
				runtimes = {
					{
						name = "JavaSE-17",
						path = "C:/Program Files/Java/jdk-17/", -- 检查您的JDK路径
						default = true
					}
				},
				maven = {
					downloadSources = true,
				},
				implementationsCodeLens = {
					enabled = true,
				},
				referencesCodeLens = {
					enabled = true,
				},
				lombok = {
					enabled = true
				}
			},
			trace = {
				server = "verbose"  -- 开启服务器跟踪用于调试
			},
			files = {
				exclude = {
					"**/node_modules/**",
					"**/.git/**",
					"**/build/**",
					"**/target/**",
					"**/.idea/**",
					"**/*.jar"
				}
			}
		}
	},
	on_attach = function(client, bufnr)
		-- 设置LSP按键映射
		local opts = { noremap = true, silent = true, buffer = bufnr }
		vim.keymap.set('n', 'gd', vim.lsp.buf.definition, opts)
		vim.keymap.set('n', 'K', vim.lsp.buf.hover, opts)
		vim.keymap.set('n', 'gr', vim.lsp.buf.references, opts)
		vim.keymap.set('n', 'gi', vim.lsp.buf.implementation, opts)
		vim.keymap.set('n', '<leader>rn', vim.lsp.buf.rename, opts)
		vim.keymap.set('n', '<leader>ca', vim.lsp.buf.code_action, opts)

		-- 启用文档高亮
		client.server_capabilities.documentHighlightProvider = true

		-- 自动命令组
		vim.api.nvim_create_augroup('jdtls_attach', { clear = true })

		-- 保存时格式化
		vim.api.nvim_create_autocmd('BufWritePre', {
			group = 'jdtls_attach',
			buffer = bufnr,
			callback = function()
				vim.lsp.buf.format({ async = false })
			end
		})
	end
}

-- 启动jdtls
local function start_jdtls()
	-- 检查启动器jar文件是否存在
	local launcher_jar = vim.fn.glob(jdtls_path .. 'plugins/org.eclipse.equinox.launcher_*.jar')
	if launcher_jar == '' then
		vim.notify("找不到jdtls启动器jar文件", vim.log.levels.ERROR)
		return
	end

	-- 检查lombok
	if vim.fn.filereadable(lombok_path) == 0 then
		vim.notify("Lombok未找到: " .. lombok_path, vim.log.levels.WARN)
	end

	require('jdtls').start_or_attach(jdtls_config)
end

-- 文件类型自动命令
vim.api.nvim_create_autocmd('FileType', {
	pattern = 'java',
	callback = function()
		-- 延迟启动以避免冲突
		vim.defer_fn(start_jdtls, 100)
	end
})

-- 简化的状态检查命令
vim.api.nvim_create_user_command('JDTLSStatus', function()
	local clients = vim.lsp.get_clients({ name = 'jdtls' })
	if #clients == 0 then
		print("jdtls 未运行")
	else
		for _, client in ipairs(clients) do
			print(string.format("jdtls: %s (%s)", 
				client.initialized and "已初始化" or "未初始化",
				client.id
			))
		end
	end
end, {})

-- 重新启动命令
vim.api.nvim_create_user_command('JDTLSRestart', function()
	local clients = vim.lsp.get_clients({ name = 'jdtls' })
	for _, client in ipairs(clients) do
		vim.lsp.stop_client(client.id)
	end
	vim.defer_fn(start_jdtls, 500)
	print("jdtls 重启中...")
end, {})

print("jdtls 配置已加载，路径: " .. jdtls_path)
